package com.bulletelc.apollopre.module.main;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.entity.WxShareBean;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.interfaces.listener.PermissionListener;
import com.bulletelc.apollopre.module.main.cart.CartFragment;
import com.bulletelc.apollopre.module.main.center.CenterFragment;
import com.bulletelc.apollopre.module.main.classify.ClassifyFragment;
import com.bulletelc.apollopre.module.main.home.HomeFragment;
import com.bulletelc.apollopre.module.main.home.ZDTHomeNewFragment;
import com.bulletelc.apollopre.module.user.LoginMainActivity;
import com.bulletelc.apollopre.receiver.NetworkStateReceiver;
import com.bulletelc.apollopre.utils.AppUtil;
import com.bulletelc.apollopre.utils.DateUtil;
import com.bulletelc.apollopre.utils.ImageUtil;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.ShareDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.lzy.okgo.model.Response;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.tencent.tauth.Tencent;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MainActivity extends MVPBaseActivity<MainContract.View, MainPresenter> implements MainContract.View,
        View.OnClickListener, PermissionListener {

    // views
    private Button btnTabHome;
    private Button btnTabClassify;
    private Button btnTabCart;
    private Button btnTabCenter;
    private NetworkStateReceiver networkStateReceiver;
    private ProgressDialog progressDialog;

    // data
    private int fragmentPosition = -1; // 当前的Fragment的position
    private boolean isBindService; // 是否成功绑定了Service服务
    private static boolean isExit = false; // 记录退出标志
    private Response<String> response;

    // 自定义
    private onActivityResultListener resultListener; // Fragment与Activity通讯回调接口
    private FragmentManager fragmentManager;
    private Fragment homeFragment;
    private Fragment classifyFragment;
    private Fragment cartFragment;
    private Fragment centerFragment;

    // 自定义分享
    private Tencent mTencent;
    private Bitmap weChatBip;
    public static ShareDialog cartShareDialog;

    // handel
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }

    @Override
    public int getLayoutRes() {
        return R.layout.main_activity;
    }

    @Override
    public void assignViews() {
        btnTabHome = findView(R.id.btnTabHome);
        btnTabClassify = findView(R.id.btnTabClassify);
        btnTabCart = findView(R.id.btnTabCart);
        btnTabCenter = findView(R.id.btnTabCenter);
    }
    @Override
    public void setListener() {
        btnTabHome.setOnClickListener(this);
        btnTabClassify.setOnClickListener(this);
        btnTabCart.setOnClickListener(this);
        btnTabCenter.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent != null) {
            fragmentPosition = intent.getIntExtra(IntentCode.EXTRA_KEY_FRAGMENT_POSITION, 0);
        }
        // 实例化Fragment
        //homeFragment = new HomeFragment();
        homeFragment = new ZDTHomeNewFragment();
        classifyFragment = new ClassifyFragment();
        cartFragment = new CartFragment();
        centerFragment = new CenterFragment();

        fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();

        ft.add(R.id.flContent, homeFragment);
        ft.add(R.id.flContent, classifyFragment);
        ft.add(R.id.flContent, cartFragment);
        ft.add(R.id.flContent, centerFragment);
        ft.commit();
        showFragment(homeFragment);
        btnTabHome.setSelected(true);

        // 获取储存权限，用于更新安装包
        requestRuntimePermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MainActivity.this);

        //checkLastOpenTime();

        //checkSignature();

        //updateApp();
        initShare();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        resultListener.onResultListener(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case IntentCode.REQUEST_CODE_MAIN_TO_LOGIN://从个人中心登录
                if (resultCode == IntentCode.RESULT_CODE_LOGIN_TO_MAIN) {
                    showFragment(centerFragment);
                    setTabMenuSelected(btnTabCenter);
                }
                break;
        }
    }

    /**
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                exit();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void showUpdateDialog() {

    }

    @Override
    public void onLoadingStart() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMax(100);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.btn_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        progressDialog.setCancelable(false);
        progressDialog.show();
    }


    @Override
    public void onLoadingFinish() {
        ToastUtil.showShortToast(this, R.string.toast_download_finished);
        //下载完成进入安装界面

        //安装完成删除安装包
    }

    @Override
    public void onLoadingError(Object error) {
        progressDialog.cancel();
    }

    @Override
    public void showLoadingProgress(long downloadLength, long totalLength, float fraction) {
        progressDialog.setProgress((int) (fraction * 100));
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.btnTabHome:
                setTabMenuSelected(btnTabHome);
                showFragment(homeFragment);
                break;

            case R.id.btnTabClassify:
                setTabMenuSelected(btnTabClassify);
                showFragment(classifyFragment);
                break;

            case R.id.btnTabCart:
                setTabMenuSelected(btnTabCart);
                showFragment(cartFragment);
                break;

            case R.id.btnTabCenter:
                // 获取偏好设置，是否登陆
                boolean login = SharedPreferencesUtil.getBoolean(MyApplication.getInstance(), SPKey.SP_CHECK_IS_LOGIN);
                if (login) {
                    setTabMenuSelected(btnTabCenter);
                    showFragment(centerFragment);
                } else {
                    Intent intentLogin = new Intent(this, LoginMainActivity.class);
                    intentLogin.putExtra(IntentCode.EXTRA_KEY_OPEN_LOGIN_TYPE, IntentCode.EXTRA_VALUE_MAIN_ACTIVITY);
                    startActivityForResult(intentLogin, IntentCode.REQUEST_CODE_MAIN_TO_LOGIN);
                }
                break;
        }

    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            fragmentPosition = intent.getIntExtra(IntentCode.EXTRA_KEY_FRAGMENT_POSITION, 0);
        }
        switch (fragmentPosition) {

            case 0:
                setTabMenuSelected(btnTabHome);
                showFragment(homeFragment);
                break;

            case 2:
                setTabMenuSelected(btnTabCart);
                showFragment(cartFragment);
                break;

            case 3:
                setTabMenuSelected(btnTabCenter);
                showFragment(centerFragment);
                break;
        }

    }

    @Override
    public void onAttachFragment(Fragment fragment) {

        // 解决Fragment重叠问题

        if (homeFragment == null && fragment instanceof HomeFragment) {
            homeFragment = fragment;
        }

        if (classifyFragment == null && fragment instanceof ClassifyFragment) {
            classifyFragment = fragment;
        }

        if (cartFragment == null && fragment instanceof CartFragment) {
            cartFragment = fragment;
        }

        if (centerFragment == null && fragment instanceof CenterFragment) {
            centerFragment = fragment;
        }

    }

    @Override
    protected void onResume() {

        // 广播注册，监听网络状态
        if (networkStateReceiver == null) {
            networkStateReceiver = new NetworkStateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkStateReceiver, filter);
        super.onResume();
    }

    @Override
    protected void onPause() {
        //广播注销
        unregisterReceiver(networkStateReceiver);
        super.onPause();
    }

    @Override
    public void onGranted() {
        checkLastOpenTime();
    }

    @Override
    public void onDenied(List<String> deniedPermissions) {

    }

    /**
     * 检查上次打开时间
     */
    private void checkLastOpenTime() {
        String lastOPenTime = SharedPreferencesUtil.getString(this, SPKey.SP_LAST_OPEN_TIME); // 默认返回""
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = simpleDateFormat1.format(new Date()); // 转换为yyyy-MM-dd HH:mm:ss 格式
        if ("".equals(lastOPenTime)) {
            checkUpdate();
            SharedPreferencesUtil.putString(this, SPKey.SP_LAST_OPEN_TIME, nowTime);
        } else {
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date1 = simpleDateFormat1.parse(nowTime);
                Date date2 = simpleDateFormat2.parse(lastOPenTime);
                int differ = DateUtil.differentDaysByMillisecond(date1, date2);
                if (differ > 1) { // 相差大于一天
                    checkUpdate();
                    SharedPreferencesUtil.putString(this, SPKey.SP_LAST_OPEN_TIME, nowTime);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 蒲公英的更新
     */
    private void checkUpdate() {
        PgyUpdateManager.register(MainActivity.this,
                new UpdateManagerListener() {
                    @Override
                    public void onUpdateAvailable(final String result) {
                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);
                        final AlertDialog.Builder updateDialog = new AlertDialog.Builder(MainActivity.this);
                        updateDialog.setTitle("发现新版本，是否现在更新？")
                                .setMessage(appBean.getReleaseNote())
                                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        startDownloadTask(
                                                MainActivity.this,
                                                appBean.getDownloadURL());
                                    }
                                });
                        updateDialog.setNegativeButton("忽略", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                        updateDialog.show();
                    }

                    @Override
                    public void onNoUpdateAvailable() {

                    }
                });

    }

    /**
     * 检测更新APP
     */
    private void updateApp() {
        int versionCode = AppUtil.getVersionCode(this);
        presenter.checkVersion();
        //异步请求服务器获取最新版本，与本地版本进行对比

        //若有新版本,(是否每次提示,还是一两天内提醒一次)弹框提示客户是否下载

        //用户确定下载:(指定下载路径),弹出进度条显示进度

        //下载完毕,询问用户是否安装
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtil.showShortToast(this, "再按一次退出");
            // 利用handle延时更新isExit
            handler.sendEmptyMessageDelayed(0, 2000);
        } else {
            //SharedPreferencesUtil.putBoolean(MyApplication.getInstance(), SPKey.SP_CHECK_ISLOAD_AVATAR, true);
            finish();
            System.exit(0); // 杀死进程
        }
    }

    /**
     * 签名认证
     */
//    private void checkSignature() {
//        boolean check_signature = SharedPreferencesUtil.getBoolean(this, SPKey.SP_CHECK_SIGNATURE);
//        //if (!check_signature) {
//        if (true) {
//            String data = "13025559670";
//            Map<String, Map<String, String>> map = new HashMap<>();
//            Map<String, String> map2 = new HashMap<>();
//            map2.put("data", data);
//            map2.put("encrypt_data", EncryptUtil.sha256(data));
//
//            map.put("SignatureForm", map2);
//
//            //JSONObject obj = (JSONObject) JSONObject.toJSON(map);
//            //String objStr = obj.toString();
//
//            RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), objStr);
//            OkGo.<String>post(NetWorkPath.POST_CHECK_SIGNATURE)
//                    .upRequestBody(body)
//                    .execute(new StringCallback() {
//                        @Override
//                        public void onSuccess(Response<String> response) {
//                            LogUtil.i(response.body().toString());
//
//                            //
//                            SharedPreferencesUtil.putBoolean(MainActivity.this, SPKey.SP_CHECK_SIGNATURE, true);
//                        }
//                    });
//        }
//
//    }

    /**
     * 选中底部菜单中的某项
     *
     * @param btn 被点击的按钮的对象
     */
    private void setTabMenuSelected(Button btn) {
        btnTabHome.setSelected(false);
        btnTabClassify.setSelected(false);
        btnTabCart.setSelected(false);
        btnTabCenter.setSelected(false);
        btn.setSelected(true);
    }

    /**
     * 显示fragment
     *
     * @param fragment
     */
    private void showFragment(Fragment fragment) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.hide(homeFragment);
        ft.hide(classifyFragment);
        ft.hide(cartFragment);
        ft.hide(centerFragment);
        ft.show(fragment);
        ft.commit();
    }

    public interface onActivityResultListener {
        void onResultListener(int requestCode, int resultCode, Intent data);
    }

    /**
     * 打开分类Fragment
     */
    public void showClassify() {
        showFragment(classifyFragment);
        setTabMenuSelected(btnTabClassify);
    }

    /**
     * 初始化分享
     */
    private void initShare() {
        mTencent = Tencent.createInstance(GlobalConfig.QQ_APP_ID, this.getApplicationContext());
        cartShareDialog = new ShareDialog(this, mTencent);
    }

    /**
     * 更新购物车分享内容
     */
    public void showCartDialog(WxShareBean wxShareBean) {
        cartShareDialog.setWxShareBean(wxShareBean);

        // 获取微信分享的图片
        Glide.with(this).load(wxShareBean.getIcon()).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) resource;
                weChatBip = bitmapDrawable.getBitmap();
                cartShareDialog.setBitmap(ImageUtil.compressByScale(weChatBip, 120, 120, false));
            }
        });

        cartShareDialog.showShareDialog();

    }

    public void setOnActivityResultListener(onActivityResultListener resultListener) {
        this.resultListener = resultListener;
    }

}
